"""
menuMaker.py

This is to create Athabaskan's menu. It also burps babies and
heightens the senses of people with green eyes and German accents.

The MenuHandler class is a Singleton (Borg-implementation) that must
be initialised with a call to SetState(wx.Frame) before any use of
its other methods.

"""

def _(s): return s

import wx, sys
import HistoryHandler
from ..dialogs import UserMessage
from ..utils import Curry, ImportHandler
from settings import UserSettings

class MenuHandler:
    _shared_state = {}
    MENU_NON_ESSENTIAL = frozenset([50])
    MENU_REMOVE_DB = frozenset([150])
    
    def __init__(self):
        self.__dict__ = self._shared_state
        
    def setState(self, mainWindow):
        self.mainWindow = mainWindow
        self.userSettings = UserSettings.UserSettings()
        self.importHandler = ImportHandler.ImportHandler()
#        self.filehistory = mainWindow.fileHistory
#        self.dbmenu = None
        self.menuIDs = set()
        self.savedMenus = {}
        
        """
        Quick explanation: each menu entry consists of:
        1) The entry name
        2) The status text help message
        3) The function to bind to it
        4) The 'class', used in enabling/disabling items later on
        OR
        wx.ID_SEPARATOR, which will accomplish the obvious
        OR
        a function name to call at the appropriate moment
        """
        self.mainMenuList = [
            (_("&File"), [
                (_("&Open\tCtrl+O"),
                 _("Open File"),
                 "Open", 0),
                (_("&Save\tCtrl+S"),
                 _("Save File"),
                 "Save", 50),
                (_("Save &As\tCtrl+Shift+S"),
                 _("Save File As"),
                 "SaveAs", 50),
                wx.ID_SEPARATOR,
                (_("&Close"),
                 _("Close File"),
                 "Close", 50),
                wx.ID_SEPARATOR,
                (_("&Import Website"),
                 _("Import Website"),
                 "ImportWebsite", 50),
                (_("&Export Website"),
                 _("Export Website"),
                 "ExportWebsite", 50),
                wx.ID_SEPARATOR,
                (_("C&leanup File"),
                 _("Cleanup File"),
                 "CleanupFile", 50),
                (_("&Roll-back"),
                 _("Roll-back"),
                 "Rollback", 50),
                wx.ID_SEPARATOR,
                (_("Recover and &Fix"),
                 _("Recover and Fix"),
                 "Recover", 0),
                wx.ID_SEPARATOR,
                # File History sub-menu goes here
                self.appendHistory,
                wx.ID_SEPARATOR,
                (_("E&xit\tAlt-X"),
                 _("Exit"),
                 "CloseWindow", 0),
                ]),
            (_("&Server"), [
                (_("Sta&rt Server"),
                 _("Start Apache Server"),
                 "StartServer", 0),
                (_("St&op Server"),
                 _("Stop Apache Server"),
                 "StopServer", 0),
                (_("&Restart Server"),
                 _("Restart Apache Server"),
                 "RestartServer", 0),
                (_("&Graceful Server Restart"),
                 _("Restart Apache Server Gracefully"),
                 "GracefulRestart", 0),
                ]),
            (_("&Wizard"), [
                (_("&Proxy"),
                 _("Configure a Proxy"),
                 "ProxyWizard", 50),
                (_("&Quota"),
                 _("Set Quotas for Users"),
                 "QuotaWizard", 50),
                ]),
            (_("&Advanced"), [
                # Modules go here
                self.appendModules,
                wx.ID_SEPARATOR,
                (_("&LDAP"),
                 _("LDAP Settings"),
                 "LDAP", 50),
                (_("&Unicode"),
                 _("Unicode Settings"),
                 "Unicode", 50),
                (_("&Charset"),
                 _("Charset Settings"),
                 "Charset", 50),
                (_("&Filters"),
                 _("Filters Settings"),
                 "Filters", 50),
                ]),
            (_("&Database"), [
                (_("&Add Database"),
                 _("Add Database"),
                 "AddDB", 0),
                (_("&Remove Database"),
                 _("Remove Database"),
                 "RemoveDB", 150),
                wx.ID_SEPARATOR,
                ## Databases get inserted here
                self.appendDatabaseMenu,
                ]),
            (_("H&istory"), [
                (_("&View History\tCtrl+H"),
                 _("View History"),
                 "ViewHistory", 0),
                (_("&Clear History"),
                 _("Clear History"),
                 "ClearHistory", 0),
                ]),
            (_("S&ettings"), [
                (_("&User Preferences"),
                 _("User Preferences"),
                 "UserPrefs", 0),
                ]),
            (_("&Help"), [
                (_("&Contents\tF1"),
                 _("Contents"),
                 "HelpContents", 0),
                wx.ID_SEPARATOR,
                (_("&About"),
                 _("About Athabaskan"),
                 "AboutAthabaskan", 0),
                ]),
        ]
        self.subMenuModules = (
            _("&Modules"), [
                (_("&Add Modules"),
                 _("Add Modules"),
                 "AddModules", 50),
                (_("&Remove Modules"),
                 _("Remove Modules"),
                 "RemoveModules", 50),
                ]
        )
        self.recentHistory = _("Recent Files")
        self.doMenu()
        return self
    
    def doMenu(self):
        """
        Create Athabaskan's main menu
        """
        mainmenu = wx.MenuBar()
        for m in self.mainMenuList:
            menu = wx.Menu()
            for vals in m[1]:
                if vals == wx.ID_SEPARATOR:
                    menu.AppendSeparator()
                elif type(vals) == tuple:
                    self.appendItem(menu, vals)
                else: #type(vals) == instancemethod
                    vals(menu)
            mainmenu.Append(menu, m[0])
        self.mainWindow.SetMenuBar(mainmenu)
        return self.menuIDs
    
    def appendItem(self, menu, (menutxt, sbtxt, module, clss)):
        id = wx.NewId()
#        if clss != 0:
        self.menuIDs.add((id, clss))
        print id, clss, menutxt
        item = menu.Append(id, menutxt, sbtxt)
        self.importHandler.bindMenuEvent(item, module)
    
    def appendHistory(self, menu):
        submenu = wx.Menu()
        id = wx.NewId()
        self.menuIDs.add((id, 0))
        self.savedMenus["history"] = id
#        self.filehistory.UseMenu(submenu)
#        [self.filehistory.AddFileToHistory(i)
#                     for i in self.userSettings.fileHistoryList()]
#        id = wx.NewId()
#        menu.AppendMenu(id, self.recentHistory, submenu)

    def appendModules(self, menu):
        submenu = wx.Menu()
        for vals in self.subMenuModules[1]:
            self.appendItem(submenu, vals)
        id = wx.NewId()
        self.menuIDs.add((id, 50))
        self.savedMenus["module"] = id
        menu.AppendMenu(id, self.subMenuModules[0], submenu)
    
    def appendDatabaseMenu(self, menu):
        id = wx.NewId()
        self.menuIDs.add((id, 0))
        self.savedMenus["database"] = id
#        self.dbmenu = menu
    
    def setEnabled(self, menuSet, enabled):
        menubar = self.mainWindow.GetMenuBar()
        print self.menuIDs
        for (id, clss) in self.menuIDs:
            if clss in menuSet:
            	pass
#x = menubar.GetLabel(id)#.Enable(enabled)
#                print x, clss, menuSet
